package com.renbang.action.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.renbang.dao.sqlsession.DBUtils;
import com.renbang.model.common.AjaxResult;
import com.renbang.model.common.Page;
import com.renbang.model.finance.Analysis;
import com.renbang.model.finance.Dictionary;
import com.renbang.model.finance.FinanceOrg;
import com.renbang.model.sys.SysLog;
import com.renbang.model.sys.SysUser;
import com.renbang.service.sys.SysFunServiceImp;
import com.renbang.service.sys.SysLogServiceImp;
import com.renbang.service.sys.SysPowerServiceImp;
import com.renbang.service.sys.SysUserServiceImp;
import com.renbang.service.finance.FinanceOrgService;
import com.renbang.service.finance.DictionaryService;
import com.renbang.utils.EncrypUtil;

@Controller
@RequestMapping(value = "/common")
public class CommonAction {
	@Value("#{dataSource['url']}")
	private String URL;
	@Value("#{dataSource['driverClassName']}")
	private String DRIVER;
	@Value("#{dataSource['username']}")
	private String USER;
	@Value("#{dataSource['password']}")
	private String PASS;

	@Autowired
	SysUserServiceImp sysUserServiceImp;
	@Autowired
	SysLogServiceImp sysLogServiceImp;
	@Autowired
	SysPowerServiceImp sysPowerServiceImp;
	@Autowired
	SysFunServiceImp sysFunServiceImp;
	@Autowired
	FinanceOrgService financeOrgService;
	@Autowired
	DictionaryService dictionaryService;
	private static Logger logger = Logger.getLogger(CommonAction.class);

	/** 获得请求的动态参数做转发 **/
	@RequestMapping(value = "/{page}")
	public String redirect(@PathVariable("page") String page) {
		DBUtils.setConnection(DRIVER, URL, USER, PASS);
		return "common/" + page;
	}

	@RequestMapping(value = "/FinanceOrgMain")
	public String FinanceOrgMain(FinanceOrg financeOrg,
			HttpServletRequest request) {
		financeOrg = new FinanceOrg();
		List<FinanceOrg> forg = financeOrgService.findBydistinct(financeOrg);
		List<Analysis> list = new ArrayList<Analysis>();
		for (FinanceOrg f : forg) {
			Analysis a = new Analysis();
			a.setArea(f.getArea());
			FinanceOrg obj = new FinanceOrg();
			obj.setOrgStatus(1);
			obj.setArea(f.getArea());
			a.setNumber(financeOrgService.findTotal(obj));
			list.add(a);
		}
		System.out.println("CommonAction.FinanceOrgMain()" + list.size());
		request.setAttribute("List", list);
		return "common/FinanceOrg-main";
	}

	@RequestMapping(value = "/FinanceOrgHome")
	public String FinanceOrgHome(FinanceOrg financeOrg,
			HttpServletRequest request, HttpServletResponse response) {
		int t = 0;
		System.out.println(financeOrg);
		FinanceOrg status = new FinanceOrg();
		status.setOrgStatus(1);
		int sum = financeOrgService.findTotal(status);
		request.getSession().setAttribute("sum", sum);
		if (financeOrg.getOrgType() != null) {
			try {
				String orgType = new String(financeOrg.getOrgType().getBytes(
						"iso8859-1"), "utf-8");
				System.out.println(orgType);
				financeOrg.setOrgType(orgType);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (financeOrg.getArea() != null && financeOrg.getArea() != "") {
			try {
				String Area = new String(financeOrg.getArea().getBytes(
						"iso8859-1"), "utf-8");
				System.out.println(Area);
				financeOrg.setArea(Area);
				t = 1;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// 区域是省直或者带了区县重定向到subList页
			if (financeOrg.getArea().contains("省直")) {
				System.out.println("getOrgType"+financeOrg.getOrgType());
				request.setAttribute("obj", financeOrg);
				return "common/FinanceOrg-subList";

			} else if (financeOrg.getArea().contains("-")) {
				String[] areaAndZone = financeOrg.getArea().split("-");
				/*String param = "?area=" + areaAndZone[0] + "&zone="
						+ areaAndZone[1];*/
				financeOrg.setArea(areaAndZone[0]);;
				financeOrg.setZone(areaAndZone[1]);
				request.setAttribute("obj", financeOrg);
				return "common/FinanceOrg-subList";
				//response.sendRedirect();
			}

		}
		request.setAttribute("obj", financeOrg);
		List<FinanceOrg> forg = financeOrgService.findBydistinct(financeOrg);
		List<Analysis> list = new ArrayList<Analysis>();
		for (FinanceOrg f : forg) {
			FinanceOrg obj = new FinanceOrg();
			obj.setArea(f.getArea());
			obj.setOrgStatus(1);
			Analysis a = new Analysis();
			a.setArea(f.getArea());
			if (t == 1) {
				a.setArea(a.getArea() + "-" + f.getZone());
				obj.setZone(f.getZone());
			}
			a.setNumber(financeOrgService.findTotal(obj));
			List<FinanceOrg> lists = financeOrgService.findByModel(obj);
			if (lists.size() > 3) {
				lists = lists.subList(lists.size()-3, lists.size());
			}
			a.setOrglist(lists);
			list.add(a);
		}
		request.setAttribute("List", list);
		return "common/FinanceOrg-home";
	}
/*	//subList页面
	@RequestMapping(value = "/FinanceOrgSubList")
	public String FinanceOrgSubList(FinanceOrg financeOrg,
			HttpServletRequest request) {
		System.out.println(financeOrg);
		return "common/FinanceOrg-subList";
	}*/
	//查看详请
	@RequestMapping(value = "/FinanceOrgDetail")
	public String FinanceOrgDetail(FinanceOrg financeOrg,
			HttpServletRequest request) {
		financeOrg=financeOrgService.findById(financeOrg.getId());
		System.out.println(financeOrg);
		request.setAttribute("obj", financeOrg);
		return "common/FinanceOrg-detail";
	}
	//subList页面分页
	@RequestMapping(value = "/showFinanceOrgList")
	public @ResponseBody AjaxResult showFinanceOrgList(HttpServletRequest request,
			Page page, FinanceOrg obj) {
		if (obj.getArea() != null && obj.getArea() != "") {
			String Area;
			try {
				Area = new String(obj.getArea().getBytes(
						"iso8859-1"), "utf-8");
				System.out.println("Area"+Area);
				obj.setArea(Area);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(obj.getZone() != null && obj.getZone() != ""){
				String Zone;
				try {
					Zone = new String(obj.getZone().getBytes(
							"iso8859-1"), "utf-8");
					System.out.println("zone"+Zone);
					obj.setZone(Zone);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			System.out.println("OrgType"+obj.getOrgType());
			if(obj.getOrgType() != null && obj.getOrgType() != ""){
				String OrgType;
				try {
					OrgType = new String(obj.getOrgType().getBytes(
							"iso8859-1"), "utf-8");
					System.out.println("OrgType"+OrgType);
					obj.setOrgType(OrgType);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		obj.setOrgStatus(1);
		Integer count = financeOrgService.findTotal(obj);
		System.out.println(obj);
		return new AjaxResult(AjaxResult.STATUS_OK, page.getCurrpage() + "",
				"数据加载成功", financeOrgService.findInPage(obj, page), count);
	}
	
	@RequestMapping(value = "/enter")
	public @ResponseBody AjaxResult doLogin(SysUser sysUser, String UserName,
			String userPass, HttpServletRequest request) {
		System.out.println(sysUser);
		if (sysUser.getUserAccount() != null && sysUser.getUserAccount() != ""
				&& sysUser.getUserPass() != null && sysUser.getUserPass() != "") {
			try {
				sysUser.setUserPass(EncrypUtil.getMD5(sysUser.getUserPass()));
				System.out.println(sysUser);
			} catch (UnsupportedEncodingException e) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "登录失败");
			}
			System.out.println(sysUser);
			List<SysUser> list = sysUserServiceImp.findByModel(sysUser);
			System.out.println(list);
			if (list.size() > 0) {
				sysUser = list.get(0);
				if (sysUser.getUserStatus().equals("activate")) {
					SysLog log = new SysLog();
					log.setIp(getRemoteHost(request));
					log.setUserName(sysUser.getUserName());
					log.setUserId(sysUser.getUserId());
					log.setLogContent("系统登录");
					log.setCreateTime(new Date());
					sysLogServiceImp.add(log);
					return typeCheck(sysUser, request);
				} else {
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "非激活状态");
				}
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号密码不正确 ");
			}
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号密码");

	}

	/** 根据用户类型跳转不同的管理页，暂时只设定两个类型 **/
	private AjaxResult typeCheck(SysUser sysUser, HttpServletRequest request) {
		if (sysUser.getUserType().equals("developer")) {
			request.getSession().setAttribute("user", sysUser);
			return new AjaxResult(AjaxResult.STATUS_OK, "/developer/index",
					null);
		} else {
			request.getSession().setAttribute("user", sysUser);
			return new AjaxResult(AjaxResult.STATUS_OK, "/user/index", null);
		}
	}

	@RequestMapping(value = "/loginOut")
	public String loginOut(HttpSession session) throws Exception {
		session.invalidate();
		return "redirect:/common/login";
	}

	public String getRemoteHost(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

}
